from rest_framework import serializers

from apps.users.models import User
import re


class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ['id', 'username', 'mobile', 'email']


class UserCreateSerializer(serializers.Serializer):
    id = serializers.IntegerField(read_only=True)
    username = serializers.CharField()
    mobile = serializers.CharField()
    email = serializers.CharField()
    password = serializers.CharField(write_only=True)

    def validate__username(self, value):
        # 验证用户名

        if not re.match(r'[a-zA-Z0-9]{5,20}$', value):
            raise serializers.ValidationError('用户名为5-20个字符串')
        if User.objects.filter(username=value):
            raise ValueError('用户名已经存在')
        return value

    def validate_mobile(self, value):
        # 验证手机号
        if not re.match(r'^1[3-9]\d{9}$', value):
            raise ValueError('手机号格式错误')
        if User.objects.filter(mobile=value):
            raise ValueError('手机号已经存在')
        return value

    def validate_email(self, value):
        # 验证邮箱
        pass

    def validate_password(self, password):
        # 验证密码
        pass

    def create(self, validated_data):
        # 重写创建方法，因为自带的不会对密码进行加密
        user = User.objects.create_user(**validated_data)

        return user
